package com.shuogg.transaction.controller;

import com.shuogg.transaction.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("add")
    @ResponseBody
    public Object add() {
        System.out.println(new Date().toString() + Thread.currentThread());
        return userService.addTest();
    }

    @RequestMapping("list")
    @ResponseBody
    public Object listAll() {
        System.out.println(new Date().toString() + Thread.currentThread());
        return userService.listAll();
    }

    /**
     * 结果: 智乃和心爱都加进来--> doInnerTransaction和innerTransaction均无产生事务
     *
     * @return all user
     */
    @RequestMapping("doInnerTransaction")
    @ResponseBody
    public Object doInnerTransaction() {
        userService.doInnerTransaction();
        return userService.listAll();
    }

    /**
     * 结果: 智乃和心爱都加进来--> doInnerTransaction和innerTransaction均无产生事务
     *
     * @return all user
     */
    @RequestMapping("doNoTransaction")
    @ResponseBody
    public Object doNoTransaction() {
        userService.doNoTransaction();
        return userService.listAll();
    }

    /**
     * 结果: 智乃和心爱都没加进来--> tdoInnerTransaction产生了事务
     *
     * @return all user
     */
    @RequestMapping("tdoInnerTransaction")
    @ResponseBody
    public Object tdoInnerTransaction() {
        userService.tdoInnerTransaction(); // 这里打断点然后step into会进入CglibAopProxy.DynamicAdvisedInterceptor的intercept()方法, 核心是chain.isEmpty()
        return userService.listAll();
    }


    /**
     * 测试SessionId
     *
     * @param request
     * @param session
     * @return
     */
    @RequestMapping("login")
    @ResponseBody
    public String login(HttpServletRequest request, HttpSession session) {
        session.setAttribute("userId", 12);
        System.out.println(request);
        System.out.println(session);

        System.out.println(request.getRequestedSessionId());
        System.out.println(session.getId());
        return "登录成功";
    }

    @RequestMapping("logout")
    @ResponseBody
    public String logout(HttpServletRequest request, HttpSession session) {
        session.setAttribute("userId", 13);
        System.out.println(request);
        System.out.println(session);
        return "退出成功";
    }


}
